package cn.lds.health.service.impl;

import cn.lds.health.constant.DsHealthConstant;
import cn.lds.health.dto.ResultDTO;
import cn.lds.health.entity.User;
import cn.lds.health.exception.SysException;
import cn.lds.health.mapper.UserMapper;
import cn.lds.health.service.UserService;
import cn.lds.health.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author Christopher
 * @Date 2023/8/5 19:30
 * @Version 1.0
 **/

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO<List<User>> selectUserAll() throws SysException {
		
		List<User> users = userMapper.selectUserAll();
		
		/**
		 * 如果插叙结果为null或者没有数据，跑出自定义异常
		 */
		if (!CollectionUtils.isEmpty(users)){
			throw new SysException(DsHealthConstant.Query.QUERY_ERROR);
		}
		
		return ResultDTO.buildSuccess(users);
	}
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO<User> selectUserById(Long id) throws SysException {
		
		User user = userMapper.selectUserById(id);
		if (Objects.isNull(user)){
			throw new SysException(DsHealthConstant.Query.QUERY_ERROR);
		}
		
		return ResultDTO.buildSuccess(user);
	}
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO<User> loginUser(User user) {
		
		//使用MD5对登录用户进行加密
		user.setPassword(MD5Utils.MD5(user.getPassword()));
		//使用加密后的密码进行登录操作
		User loginUser = userMapper.loginUser(user);
		
		/**
		 * 这里错误信息在登录页显示，我们不实用统一异常处理，直接返回错误信息
		 */
		if(Objects.isNull(loginUser)){
			return ResultDTO.buildError(DsHealthConstant.User.LOGIN_ERROR);
		}
		
		return ResultDTO.buildSuccess(loginUser);
	}
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO selectUserByIdNoOrMobileNo(String idNo,String mobileNo){
		User user = userMapper.selectUserByIdNoOrMobileNo(idNo, mobileNo);
		
		if (Objects.isNull(user)){
			return ResultDTO.buildError(DsHealthConstant.User.NO_USER);
		}
		
		return ResultDTO.buildSuccess(user);
	}
	
	@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
	@Override
	public ResultDTO regUser(User user) throws SysException {
		
		
		//对提交的用户密码进行加密
		user.setPassword(MD5Utils.MD5(user.getName()));
		//添加创建时间
		user.setCreateTime(new Date());
		
		int i = userMapper.regUser(user);
		
		if (i <= 0){
			throw new SysException(DsHealthConstant.Insert.ADD_ERROR);
		}
		
		return ResultDTO.buildSuccess(DsHealthConstant.Insert.ADD_SUCCESS);
	}
}